/**
水波效果，这个最好在64左右可以有比较合适的效果
*/
package kgame5.keff {
import flash.display.*;
import flash.filters.*;
import flash.geom.*;

public class WaterFace2D{
	//_____________________Property______________________
	private var damper:BitmapData;
	private var result:BitmapData;
	private var result2:BitmapData;
	private var source:BitmapData;
	private var buffer:BitmapData;
	private var output:BitmapData;
	private var surface:BitmapData;
	private var bounds:Rectangle;
	private var origin:Point;
	private var matrix:Matrix;
	private var matrix2:Matrix;
	
	private var wave:ConvolutionFilter;
	private var damp:ColorTransform;
	private var water:DisplacementMapFilter;
	
	private var rect:Rectangle;
	
	private var mc:Sprite;
	
	private var 
		W:Number,H:Number,
		W2:Number,H2:Number;
	//_____________________Method______________________
	public function WaterFace2D(p_srcBmd:BitmapData,p_W:Number=64,p_H:Number=64){
		
		W=p_W;//p_srcBmd.width;
		H=p_H;//p_srcBmd.height;
		W2=W*2;
		H2=H*2;
		
		damper= new BitmapData(W, H, false,128);//这个要是不加128就会有问题
		result= new BitmapData(W, H, false,128);
		result2= new BitmapData(W2, H2, false,128);
		source= new BitmapData(W, H, false,128);
		buffer= new BitmapData(W, H, false,128);
		output= new BitmapData(W2, H2, true,128);
		
		surface=p_srcBmd;
		
		bounds= new Rectangle(0, 0, W, H);
		origin= new Point();
		matrix= new Matrix();
		matrix2= new Matrix();
		matrix2.a = matrix2.d =2;//这个是scale的
		wave= new ConvolutionFilter(3, 3, [1, 1, 1, 1, 1, 1, 1, 1, 1], 9, 0);
		damp= new ColorTransform(0, 0, 9.960937E-001, 1, 0, 0, 2, 0);
		water= new DisplacementMapFilter(result2, origin, 4, 4, 48, 48, "ignore");
		
		rect=new Rectangle(0, 0, W2, H2);
		
		mc=new Sprite();
		var bitmap:Bitmap=new Bitmap(output);
		mc.addChild(bitmap);
	}
	public function getDO():Sprite{
		trace(mc.width,mc.height);
		return mc;
		
	}
	//水面颤抖，x,y是上面的点
    public function Damp(x:Number,y:Number){
    	var _loc2:Number = x / 2;
        var _loc1:Number = y / 2;
        source.lock();
        source.setPixel(_loc2 + 1, _loc1, 16777215);
        source.setPixel(_loc2 - 1, _loc1, 16777215);
        source.setPixel(_loc2, _loc1 + 1, 16777215);
        source.setPixel(_loc2, _loc1 - 1, 16777215);
        source.setPixel(_loc2, _loc1, 16777215);
        source.unlock();
    }
    public function update(){
	    //result.lock();
	    result.applyFilter(source, bounds, origin, wave);
	    result.draw(result, matrix, null, "add");
	    result.draw(buffer, matrix, null, "difference");
	    result.draw(result, matrix, damp);
		//result.unlock();
		
	    result2.draw(result, matrix2, null, null, null, true);
		
		//output.lock();
	    output.applyFilter(surface, rect, origin, water);
	    //output.unlock();
		
		buffer = source;
	    source = result.clone();
    }
}//end of class
}